﻿using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BLL.Wage
{
    /// <summary>
    /// 绩效绩效
    /// </summary>
    public class ProductWageBLL : SysFrameWork.PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        OperateModel oper;
        ReturnResult rsl;
        List<OperateModel> operList;
        SysFrameWork.SystemBLL sysBLL;
        public ProductWageBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            sysBLL = new SysFrameWork.SystemBLL();
        }
        /// <summary>
        /// 绩效参数配置
        /// </summary>
        /// <returns></returns>
        public ReturnResult GetWageConfig()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_parameters_info where ");
                sb.Append("parCode='funwage'");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    var par = table.Rows[0]["parValue"].ToString();
                    var list = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(par);
                    for (int i = 0; i < list.Count; i++)
                    {
                        var value = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(list[i]["value"].ToString());
                        list[i]["value"] = value;
                    }
                    rsl.Result = true;
                    rsl.Data = list;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 基础绩效更新方法
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="childText">子工序文本</param>
        /// <returns></returns>
        public ReturnResult UpdateFunWage(string datas, string childText)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                oper = new OperateModel();
                var wage = JsonConvert.DeserializeObject<DbFunWageInfo>(datas);
                if (wage.id == null || wage.id == 0)
                {
                    #region 添加
                    wage.isdel = 0;
                    wage.createtime = getNow();
                    wage.createtuser = userLogin.UserInfo().userCode;
                    oper.Types = OperateModel.OperateType.Add;
                    #endregion
                }
                else
                {
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                }
                oper.Data = wage;
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 绩效数据信息
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetFunWageList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {

                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                sb.Append(" isdel=0 ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("V_FunWage_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        /// <summary>
        /// 根据id获取基础绩效
        /// </summary>
        /// <param name="dataId">数据id</param>
        /// <returns></returns>
        public ReturnResult GetFunWageById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_FunWage_info where id=" + dataId);
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 绩效删除方法
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelFunWage(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                DbFunWageInfo wage = new DbFunWageInfo();
                wage.id = int.Parse(dataId);
                wage.isdel = 1;
                wage.delDate = getNow();
                wage.delUser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Conditions = "id";
                oper.Data = wage;
                oper.Types = OperateModel.OperateType.Edit;
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult getGongXuGSList(string pageIndex, string pageSize, ref string pageCount, string condition, bool inHouse = false)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("isdel=0 ");
                if (inHouse)
                {
                    sb.Append(" and ctype='bglx' and isdel=0");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "typeCode")
                            {
                                sb.Append(obj.Name + "='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }
                rsl.Data = cmd.PageList<viewFunWageGongshi>("V_FunWage_gongshi", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取计算公式
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult getCommonDataById(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_FunWage_gongshi where ");
                sb.Append("id=" + dataId);
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 员工绩效公式
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <param name="inHouse"></param>
        /// <returns></returns>
        public ReturnResult EmployeeWage(string pageIndex, string pageSize, ref string pageCount, string condition, bool inHouse = false)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");

                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);

                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append(" convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }
                rsl.Data = cmd.PageList("V_EmployeeWage_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>

        /// <summary>
        /// 更新绩效数据
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult UpdateCommonData(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                if (string.IsNullOrWhiteSpace(json["id"].ToString()) || json["id"].ToString() == "0")
                {
                    DbCommonData cm = new DbCommonData();
                    cm.parentCode = json["gxCode"].ToString();
                    cm.orderNum = json["gxChild"].ToString();
                    if (json.Property("proType") != null)
                    {
                        cm.specFile = json["proType"].ToString();
                    }
                    cm.cValues = json["cValues"].ToString();
                    cm.cType = "sysjxgs";
                    cm.cMemo = "生产绩效公式";
                    cm.isDel = 0;
                    cm.status = "Y";
                    cm.createtime = getNow();
                    rsl = cmd.Add(cm);
                }
                else
                {
                    DbCommonData cm = new DbCommonData();
                    cm.parentCode = json["gxCode"].ToString();
                    cm.orderNum = json["gxChild"].ToString();
                    if (json.Property("proType") != null)
                    {
                        cm.specFile = json["proType"].ToString();
                    }
                    cm.cValues = json["cValues"].ToString();
                    cm.isDel = 0;
                    cm.status = "Y";
                    cm.id = int.Parse(json["id"].ToString());
                    oper = new OperateModel();
                    oper.Data = cm;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    rsl = cmd.Edit(oper);
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取生产绩效类型
        /// </summary>
        /// <param name="gxCode">工序编码</param>
        /// <returns></returns>
        public ReturnResult getProductWageType()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where parentCode='3'");
                sb.Append(" and cType='gxjx' and isdel=0");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 生产类型
        /// </summary>
        /// <returns></returns>
        public ReturnResult getProductType(string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where (orderNum='" + gxCode + "'");
                sb.Append(" and cType='scgxlx' and isdel=0) or cType='common'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 绩效确认
        /// </summary>
        /// <param name="ids">绩效id集合</param>
        /// <param name="result">确认结果</param>
        /// <returns></returns>
        public ReturnResult confirmWage(string ids, string result)
        {
            rsl = new ReturnResult();
            try
            {
                List<string> sqlList = new List<string>();
                StringBuilder sb = new StringBuilder();
                sb.Append("update pw_employeeWage_info set status='" + result + "'");
                sb.Append(" where id in(" + ids + ")");
                sqlList.Add(sb.ToString());
                sb = new StringBuilder();
                sb.Append("insert into sys_Approves_record values('PWC','-','" + result + "'");
                sb.Append(",'" + userLogin.UserInfo().userCode + "','" + getNow() + "','" + ids + "')");
                sqlList.Add(sb.ToString());
                if (sqlList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(sqlList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 绩效计算方法
        /// </summary>
        /// <param name="json">参数</param>
        /// <param name="barCode">关联条码</param>
        /// <param name="createuser">创建人</param>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public ReturnResult ProductMoney(JObject json, string barCode, string createuser, ref List<OperateModel> list)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where cType='GXGS' and ");
                sb.Append("parentCode='" + json["gxCode"].ToString() + "' and isdel=0");
                var gsTable = cmd.GetDataTable(sb.ToString());//公式信息
                if (gsTable.Rows.Count < 1)
                {
                    rsl.Message = string.Format("此工序没有绩效公式:{0}", json["gxCode"].ToString());
                    return rsl;
                }
                #region 获取生产工序的表单数据以及调整金额
                sb.Clear();
                sb.Append("select gxContents,priceAdjust from pi_ProductionPlan_process where ");
                sb.Append("plCode='" + json["plCode"].ToString() + "' and gxCode='" + json["gxCode"].ToString() + "'");
                sb.Append(" and proCode='" + json["proCode"].ToString() + "'");
                var gxFormTable = cmd.GetDataTable(sb.ToString());
                JObject gxJson = new JObject();
                double tzjg = 0;//工序调整价格
                if (gxFormTable.Rows.Count > 0 && gxFormTable.Rows[0][0].ToString() != "--")
                {
                    gxJson = JsonConvert.DeserializeObject<JObject>(gxFormTable.Rows[0]["gxContents"].ToString());
                    if (gxFormTable.Rows[0]["priceAdjust"] != null && !string.IsNullOrWhiteSpace(gxFormTable.Rows[0]["priceAdjust"].ToString()))
                    {
                        tzjg = double.Parse(gxFormTable.Rows[0]["priceAdjust"].ToString());
                    }
                }
                #endregion

                #region 获取生产计划数据
                sb.Clear();
                sb.Append("select * from V_ProductionPlan_products where plCode='" + json["plCode"].ToString() + "'");
                sb.Append(" and proCode='" + json["proCode"].ToString() + "'");
                var planTable = cmd.GetDataTable(sb.ToString());
                #endregion

                string msg = "", unitWage = "";
                formatSCGs(gsTable.Rows[0]["cValues"].ToString(), gxJson, planTable, json["gxCode"].ToString(), ref unitWage, ref msg);
                if (unitWage == "")
                {
                    rsl.Message = msg;
                    return rsl;
                }


                sb.Clear();
                sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where parCode='wageValue'");
                var parTable = cmd.GetDataTable(sb.ToString());//绩效数据
                string wageSet = "";
                if (parTable.Rows.Count > 0 && !string.IsNullOrWhiteSpace(parTable.Rows[0][0].ToString()))
                {
                    wageSet = parTable.Rows[0][0].ToString();
                }
                #region 人员岗位
                var uArr = json["userCodes"].ToString().Split(',');
                foreach (string u in uArr)
                {
                    if (!string.IsNullOrWhiteSpace(u))
                    {
                        var usArr = u.Split('-');
                        double zhanbi = double.Parse(usArr[2]);
                        double sl = double.Parse(json["number"].ToString());

                        #region 数量取值
                        if (!string.IsNullOrWhiteSpace(wageSet))
                        {
                            var wJson = JsonConvert.DeserializeObject<List<JObject>>(wageSet);
                            foreach (var j in wJson)
                            {
                                if (j["gxCode"].ToString() == json["gxCode"].ToString())
                                {
                                    sl = double.Parse(json[j["file"].ToString()].ToString());
                                    break;
                                }
                            }
                        }
                        #endregion
                        DbemployeeWage wage = new DbemployeeWage();
                        wage.barCode = barCode;
                        wage.userCode = usArr[0];
                        wage.gangwei = usArr[1];
                        wage.zhanbi = "";
                        wage.status = "approving";//默认为待审核
                        wage.plCode = json["plCode"].ToString();
                        wage.dataId = json["dataId"].ToString();//排产单Id
                        wage.memo = string.Format("调整单价：{0}", tzjg);
                        //   wage.num = sl.ToString();
                        wage.createtime = getNow();
                        wage.createuser = createuser;
                        if (DateTime.Now.Hour < int.Parse(Tools.ConfigReader.Reader["WageTimeEnd"]))
                        {
                            wage.happenDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            wage.happenDate = getNowDate();
                        }
                        wage.isdel = 0;
                        wage.uPrice = Convert.ToString(double.Parse(unitWage) + tzjg);
                        if (!string.IsNullOrWhiteSpace(barCode) && barCode != "-")
                        {
                            wage.wType = "ProRd";
                        }
                        else
                        {
                            wage.wType = "BgRd";
                        }
                        wage.gxCode = json["gxCode"].ToString();
                        wage.total = Convert.ToString(sl * double.Parse(wage.uPrice) * zhanbi);
                        wage.zhanbi = zhanbi.ToString();
                        oper = new OperateModel();
                        oper.Data = wage;
                        oper.Types = OperateModel.OperateType.Add;
                        list.Add(oper);
                    }
                }
                #endregion
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 毛纺行业绩效公司
        /// </summary>
        /// <param name="json"></param>
        /// <param name="barCode"></param>
        /// <param name="createuser"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public ReturnResult ProductMoney_MF(JObject json, string barCode, string createuser, ref List<OperateModel> list)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where cType='GxCM' and ");
                sb.Append("cCode='" + json["cgxCode"] + "' and isdel=0");
                var gsTable = cmd.GetDataTable(sb.ToString());
                double scdj = 1;//生产单价
                if (gsTable.Rows.Count > 0 && gsTable.Rows[0]["cValues"] != null && !string.IsNullOrWhiteSpace(gsTable.Rows[0]["cValues"].ToString()))
                {
                    scdj = double.Parse(gsTable.Rows[0]["cValues"].ToString());
                }

                #region 人员岗位
                var uArr = json["userCodes"].ToString().Split(',');
                int scsl = int.Parse(json["quaNumber"].ToString()) / uArr.Length;
                foreach (string u in uArr)
                {
                    if (!string.IsNullOrWhiteSpace(u))
                    {
                        var usArr = u.Split('-');
                        DbemployeeWage wage = new DbemployeeWage();
                        wage.barCode = barCode;
                        wage.userCode = usArr[0];
                        wage.gangwei = "";
                        wage.zhanbi = "";
                        wage.happenDate = json["hDate"].ToString();
                        wage.status = "approving";//默认为待审核
                        wage.plCode = json["plCode"].ToString();
                        wage.dataId = json["dataId"].ToString();//排产单Id
                        wage.memo = string.Format("数量计算：{0}/{1}", json["quaNumber"].ToString(), uArr.Length);
                        //  wage.num = scsl.ToString();
                        wage.createtime = getNow();
                        wage.createuser = createuser;
                        wage.isdel = 0;
                        wage.uPrice = scdj.ToString();
                        if (!string.IsNullOrWhiteSpace(barCode) && barCode != "-")
                        {
                            wage.wType = "ProRd";
                        }
                        else
                        {
                            wage.wType = "BgRd";
                        }
                        wage.gxCode = json["gxCode"].ToString();
                        wage.total = Convert.ToString(scdj * scsl);
                        oper = new OperateModel();
                        oper.Data = wage;
                        oper.Types = OperateModel.OperateType.Add;
                        list.Add(oper);
                    }
                }
                #endregion
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产绩效单价计算方法
        /// </summary>
        /// <param name="gsStr">公式字符串</param>
        /// <param name="gfJson">生产工序Json</param>
        /// <param name="planTable">生产计划数据</param>
        /// <param name="gxCode">工序编码</param>
        /// <param name="value">单价值</param>
        /// <param name="msg">错误消息</param>
        /// <param name="isPro"></param>
        /// <param name="proGxCode"></param>
        private void formatSCGs(string gsStr, JObject gfJson, DataTable planTable, string gxCode, ref string value, ref string msg)
        {
            StringBuilder sb = new StringBuilder();
            value = "0";
            #region 获取绩效生产数据
            sb.Append("select * from fun_Wages_info where ");
            sb.Append("isdel=0 and gxCode='" + gxCode + "'");
            var wageTable = cmd.GetDataTable(sb.ToString());
            if (wageTable.Rows.Count < 1)
            {
                msg = string.Format("没有此工序的绩效数据信息:{0}", gxCode);
                return;
            }
            #endregion

            gsStr = gsStr.Replace("（", "(").Replace("）", ")");
            string newGs = gsStr.Replace("[", "").Replace("]", "");

            Regex reg = new Regex(@"(?is)(?<=\[)[^\)]+(?=\])");
            MatchCollection mc = reg.Matches(gsStr);
            foreach (Match m in mc)
            {
                if (!string.IsNullOrWhiteSpace(m.Value))
                {
                    string fName = m.Value.Trim();
                    string fValue = "";
                    if (gfJson == null || gfJson.Property(fName) == null)
                    {
                        #region 计划主信息取数
                        if (planTable.Columns.Contains(fName) && planTable.Rows[0][fName] != null)
                        {
                            fValue = planTable.Rows[0][fName].ToString();
                        }
                        #endregion
                    }
                    else
                    {
                        fValue = gfJson[fName].ToString();//生产工序表单根据字段取值
                    }
                    if (string.IsNullOrWhiteSpace(fValue))
                    {
                        msg = "字段值无法获取数值：" + fName;
                        return;
                    }
                    var dr = wageTable.Select("fileCode='" + fName + "'");
                    string money = "0";
                    foreach (DataRow r in dr)
                    {
                        if (double.Parse(fValue) >= double.Parse(r["minValue"].ToString()) && double.Parse(fValue) <= double.Parse(r["maxValue"].ToString()))
                        {
                            money = r["money"].ToString();
                            break;
                        }
                    }
                    newGs = newGs.Replace(fName, money);
                }
            }
            if (!string.IsNullOrWhiteSpace(newGs))
            {

                var u_value = new DataTable().Compute(newGs, "");
                value = u_value.ToString();
            }

        }


        /// <summary>
        /// 员工绩效数据显示
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult GetEmployeeWageInfo(string condition)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select * from V_Wage_EmpWage where isdel=0 ");
                #region 检索条件
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        if (obj.Name == "sDate")
                        {
                            sb.Append(" convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                        }
                        else if (obj.Name == "eDate")
                        {
                            sb.Append(" convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                        }
                        else
                        {
                            sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                sb.Append(" order by userCode,gxCode ");
                #endregion

                var table = cmd.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                List<Dictionary<string, string>> dList = new List<Dictionary<string, string>>();
                Dictionary<string, string> d;
                foreach (DataRow r in table.Rows)
                {
                    string usCode = r["userCode"].ToString();
                    string gxCode = r["gxCode"].ToString();
                    string uPrice = r["uPrice"].ToString();
                    string key = string.Format("{0}-{1}-{2}", usCode, gxCode, uPrice);
                    if (!reList.Contains(key))
                    {
                        var dr = table.Select("userCode='" + usCode + "' and gxCode='" + gxCode + "' and uPrice='" + uPrice + "'");
                        double yNum = 0, nNum = 0, total = 0;
                        foreach (DataRow row in dr)
                        {
                            yNum += double.Parse(row["yNum"].ToString());
                            nNum += double.Parse(row["nNum"].ToString());
                            total += double.Parse(row["total"].ToString());
                        }
                        d = new Dictionary<string, string>();
                        d["happenDate"] = string.Format("{0}至{1}", json["sDate"].ToString(), json["eDate"].ToString());
                        d["userName"] = r["userName"].ToString();
                        d["userCode"] = r["userCode"].ToString();
                        d["gxCode"] = r["gxCode"].ToString();
                        d["gxName"] = r["gxName"].ToString();
                        //d["uPrice"] = r["uPrice"].ToString();
                        d["yPrice"] = r["yPrice"].ToString();
                        d["nPrice"] = r["nPrice"].ToString();
                        //d["number"] = string.Format("{0}/{1}", yNum, nNum);
                        d["yNum"] = yNum.ToString();
                        d["nNum"] = nNum.ToString();
                        d["total"] = total.ToString();
                        dList.Add(d);
                        reList.Add(key);
                    }


                }

                rsl.Data = dList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        /// <summary>
        /// 员工生产绩效
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public DataTable EmployeeWageData(string condition)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select w.*,u.userName,cm.cName wTypeName,b.planCode,b.proCode,b.proName,b.spec,");
            sb.Append("b.c_gongjin,isnull(b.c_mishu,'0') c_mishu,b.barType from pw_employeeWage_info w");
            sb.Append(" inner join sys_users_info u on u.userCode=w.userCode");
            sb.Append(" inner join fun_CommonData_Info cm on cm.cCode=w.wType");
            sb.Append(" inner join V_BarCode_Info b on b.barCode=w.barCode and b.baseCode=u.baseCode");
            sb.Append(" and b.baseCode='" + userLogin.UserInfo().baseCode + "' where w.isdel=0  ");
            if (userLogin.UserInfo().isAdmin != 1)
            {
                sb.Append(" and wType in(select GongXu from pi_GongXuUser_set ");
                sb.Append("where usCode='" + userLogin.UserInfo().userCode + "')");
            }
            #region 检索条件
            if (!string.IsNullOrWhiteSpace(condition))
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    sb.Append(" and convert(date,w.happendate)>='" + json["sDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                {
                    sb.Append(" and convert(date,w.happendate)<='" + json["eDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["usersCode"].ToString()))
                {
                    var uArr = json["usersCode"].ToString().Split(',');
                    string ucodes = "";
                    foreach (string u in uArr)
                    {
                        if (!string.IsNullOrWhiteSpace(u))
                        {
                            ucodes += "'" + u + "',";
                        }
                    }
                    sb.Append(" and w.userCode in (" + ucodes.TrimEnd(',') + ")");
                }
                if (!string.IsNullOrWhiteSpace(json["gxCodes"].ToString()))
                {
                    var gxArr = json["gxCodes"].ToString().Split(',');
                    string codes = "";
                    foreach (string u in gxArr)
                    {
                        if (!string.IsNullOrWhiteSpace(u))
                        {
                            codes += "'" + u + "',";
                        }
                    }
                    sb.Append(" and w.wType in (" + codes.TrimEnd(',') + ")");
                }
            }
            #endregion

            return cmd.GetDataTable(sb.ToString());

        }
        /// <summary>
        /// 员工奖惩绩效
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        private DataTable EmployeeWageJC(string condition)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select * from V_WageOther_info where isdel=0 and baseCode='" + userLogin.UserInfo().baseCode + "'");
            if (userLogin.UserInfo().isAdmin != 1)
            {
                sb.Append(" and gxCode in(select GongXu from pi_GongXuUser_set ");
                sb.Append("where usCode='" + userLogin.UserInfo().userCode + "')");
            }
            #region 检索条件
            if (!string.IsNullOrWhiteSpace(condition))
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    sb.Append(" and convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                {
                    sb.Append(" and convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["usersCode"].ToString()))
                {
                    var uArr = json["usersCode"].ToString().Split(',');
                    string ucodes = "";
                    foreach (string u in uArr)
                    {
                        if (!string.IsNullOrWhiteSpace(u))
                        {
                            ucodes += "'" + u + "',";
                        }
                    }
                    sb.Append(" and usCode in (" + ucodes.TrimEnd(',') + ")");
                }
                if (!string.IsNullOrWhiteSpace(json["gxCodes"].ToString()))
                {
                    var gxArr = json["gxCodes"].ToString().Split(',');
                    string codes = "";
                    foreach (string u in gxArr)
                    {
                        if (!string.IsNullOrWhiteSpace(u))
                        {
                            codes += "'" + u + "',";
                        }
                    }
                    sb.Append(" and gxCode in (" + codes.TrimEnd(',') + ")");
                }
            }
            #endregion
            return cmd.GetDataTable(sb.ToString());
        }
        /// <summary>
        /// 员工绩效数据导出
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult EmployeeWageReport(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                string sDate = "", eDate = getNowDate();
                if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    sDate = json["sDate"].ToString();
                }
                else
                {
                    rsl.Message = "请选择开始日期";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select userCode,userName,gxName,yNum,nNum,total,uPrice,happenDate ");
                sb.Append("from V_Wage_EmpWage where isdel=0");
                var table = cmd.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                Dictionary<string, object> d;
                List<Dictionary<string, object>> dList = new List<Dictionary<string, object>>();

                foreach (DataRow r in table.Rows)
                {
                    if (!reList.Contains(r["userCode"].ToString()))
                    {
                        double total = 0, yTotal = 0, nTotal = 0;
                        var dr = table.Select("userCode='" + r["userCode"].ToString() + "'");
                        var ulist = new List<Dictionary<string, string>>();
                        d = new Dictionary<string, object>();
                        var ud = new Dictionary<string, string>();
                        foreach (DataRow udr in dr)
                        {
                            total += double.Parse(udr["total"].ToString());
                            yTotal += double.Parse(udr["yNum"].ToString());
                            nTotal += double.Parse(udr["nNum"].ToString());
                            ud["date"] = r["happenDate"].ToString();
                            ud["yNum"] = r["yNum"].ToString();
                            ud["nNum"] = r["nNum"].ToString();
                            ud["uPrice"] = r["uPrice"].ToString();
                            ud["total"] = r["total"].ToString();
                            ulist.Add(ud);
                        }
                        d["user"] = string.Format("{0}({1})", r["userName"].ToString(), r["userCode"].ToString());
                        d["yTotal"] = yTotal.ToString();
                        d["nTotal"] = nTotal.ToString();
                        d["total"] = total.ToString();
                        d["datas"] = ulist;
                        if (ulist.Count > 0)
                        {
                            dList.Add(d);
                        }

                        reList.Add(r["userCode"].ToString());
                    }
                }
                if (dList.Count > 0)
                {
                    rsl.Data = dList;
                    rsl.Result = true;
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void CreateData(Dictionary<string, string> dic, ref List<Dictionary<string, object>> dList)
        {
            var usDic = new Dictionary<string, object>();
            usDic["userName"] = dic["userName"].ToString(); ;
            var dayList = new List<Dictionary<string, object>>();
            var dayDic = new Dictionary<string, object>();
            dayDic["happenDate"] = dic["happenDate"];
            var mxList = new List<Dictionary<string, object>>();
            var mxDic = new Dictionary<string, object>();
            mxDic["plCode"] = dic["plCode"];
            mxDic["wTypeName"] = dic["wTypeName"];
            mxDic["wType"] = dic["wType"];
            mxDic["proName"] = dic["proName"];
            mxDic["spec"] = dic["spec"];
            mxDic["happenDate"] = dic["happenDate"];
            mxDic["zhongliang"] = dic["zhongliang"];
            mxDic["shuliang"] = dic["shuliang"];
            mxDic["numCount"] = dic["numCount"];
            mxDic["total"] = dic["total"];
            mxList.Add(mxDic);
            dayDic["total"] = dic["total"];
            dayDic["mx"] = mxList;
            dayList.Add(dayDic);
            usDic["mx"] = dayList;
            dList.Add(usDic);
        }
        /// <summary>
        /// 员工生产绩效
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<Dictionary<string, string>> EmpProWage(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            DataTable table = new DataTable();
            StringBuilder sb = new StringBuilder();
            sb.Append(" status='pass' ");

            #region 检索条件
            if (!string.IsNullOrWhiteSpace(condition))
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {

                        if (obj.Name == "sDate")
                        {
                            sb.Append(" and convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                        }
                        else if (obj.Name == "eDate")
                        {
                            sb.Append(" and convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                        }
                        else if (obj.Name == "userCode")
                        {
                            var uArr = json["userCode"].ToString().Split(',');
                            string codes = "";
                            foreach (string u in uArr)
                            {
                                if (!string.IsNullOrWhiteSpace(u))
                                {
                                    codes += "'" + u + "',";
                                }
                            }
                            sb.Append(" and userCode in (" + codes.TrimEnd(',') + ")");
                        }


                    }
                }
            }
            #endregion

            var list = cmd.PageList("V_Wage_ProductWage", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
            return list;
        }
        /// <summary>
        /// 员工奖惩绩效
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<Dictionary<string, string>> EmpJCWage(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            DataTable table = new DataTable();
            StringBuilder sb = new StringBuilder();
            sb.Append(" isdel=0 ");

            #region 检索条件
            if (!string.IsNullOrWhiteSpace(condition))
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {

                        if (obj.Name == "sDate")
                        {
                            sb.Append(" and convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                        }
                        else if (obj.Name == "eDate")
                        {
                            sb.Append(" and convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                        }
                        else if (obj.Name == "userCode")
                        {
                            var uArr = json["userCode"].ToString().Split(',');
                            string codes = "";
                            foreach (string u in uArr)
                            {
                                if (!string.IsNullOrWhiteSpace(u))
                                {
                                    codes += "'" + u + "',";
                                }
                            }
                            sb.Append(" and userCode in (" + codes.TrimEnd(',') + ")");
                        }


                    }
                }
            }
            #endregion

            var list = cmd.PageList("V_WageOther_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
            return list;
        }
        /// <summary>
        /// 员工绩效明细
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetEmployeeWageDetail(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_Wage_EmpWage where isdel=0 ");
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (obj.Name == "happenDate")
                            {
                                var sDate = obj.Value.ToString().Substring(0, obj.Value.ToString().IndexOf("至"));
                                var eDate = obj.Value.ToString().Substring(obj.Value.ToString().IndexOf("至") + 1);
                                sb.Append(" and convert(date,happendate) >='" + sDate + "' and convert(date,happendate) <='" + eDate + "'");
                            }
                            else
                            {
                                sb.Append(" and " + obj.Name + " ='" + obj.Value.ToString() + "' ");
                            }
                        }
                    }
                }
                #endregion
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 奖惩绩效数据保存
        /// </summary>
        /// <param name="datas">数据信息</param>
        /// <returns></returns>
        public ReturnResult SaveOtherWage(string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                DbWageOther wage;
                #region
                if (string.IsNullOrWhiteSpace(json["money"].ToString()))
                {
                    rsl.Message = "金额不允许为空";
                    return rsl;
                }

                if (string.IsNullOrWhiteSpace(json["wageType"].ToString()))
                {
                    rsl.Message = "奖惩类型不允许为空";
                    return rsl;
                }
                #endregion
                var users = json["usersCode"].ToString().Split(',');
                if (json["id"] == null || json["id"].ToString() == "")
                {
                    #region 添加
                    if (string.IsNullOrWhiteSpace(json["usersCode"].ToString()))
                    {
                        rsl.Message = "人员不允许为空";
                        return rsl;
                    }
                    foreach (string u in users)
                    {
                        if (!string.IsNullOrWhiteSpace(u))
                        {
                            wage = new DbWageOther();
                            wage.happenDate = json["happenDate"].ToString();
                            wage.memo = json["memo"].ToString();
                            wage.createtime = getNow();
                            wage.createuser = userLogin.UserInfo().userCode;
                            wage.isDel = 0;
                            wage.money = json["money"].ToString();
                            wage.userCode = u.Trim();
                            wage.gxCode = json["gxCode"].ToString();
                            wage.wageType = json["wageType"].ToString();
                            oper = new OperateModel();
                            oper.Data = wage;
                            oper.Types = OperateModel.OperateType.Add;
                            operList.Add(oper);
                        }

                    }
                    #endregion
                }
                else
                {
                    wage = new DbWageOther();
                    wage.happenDate = json["happenDate"].ToString();
                    wage.memo = json["memo"].ToString();
                    wage.createtime = getNow();
                    wage.createuser = userLogin.UserInfo().userCode;
                    wage.money = json["money"].ToString();
                    wage.wageType = json["wageType"].ToString();
                    wage.id = int.Parse(json["id"].ToString());
                    oper = new OperateModel();
                    oper.Data = wage;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 奖惩绩效列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetWageOtherList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {

                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                sb.Append(" isdel=0 and baseCode='" + userLogin.UserInfo().baseCode + "'");
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                    {
                        sb.Append(" and convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                    }
                    if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                    {
                        sb.Append(" and convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                    }
                    if (!string.IsNullOrWhiteSpace(json["usersName"].ToString()))
                    {
                        sb.Append(" and userName like '%" + json["usersName"].ToString() + "%'");
                    }
                    if (!string.IsNullOrWhiteSpace(json["sgxCode"].ToString()))
                    {
                        sb.Append(" and gxCode ='" + json["sgxCode"].ToString() + "'");
                    }
                }
                #endregion
                //sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList<ViewWageOther>("V_WageOther_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        /// <summary>
        /// 人员绩效数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getUserWageOther(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var arr = condition.Split(',');
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_WageOther_info where ");
                sb.Append("usCode='" + arr[0] + "' and happenDate='" + arr[1] + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取生产报工绩效
        /// </summary>
        /// <param name="condition">数据条件(plCode,gxCode,userCode,date)</param>
        /// <returns></returns>
        public ReturnResult getProductReportWage(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var arr = condition.Split(',');
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                StringBuilder sb = new StringBuilder();
                sb.Append("select w.*,u.userName from pw_employeeWage_info w ");
                sb.Append("inner join sys_users_info u on u.userCode=w.userCode ");
                sb.Append("where memo ");
                sb.Append("in(select memo from pi_ProductBaogong_info where plCode='" + arr[0] + "'");
                sb.Append(" and userCode='" + arr[2] + "' and happenDate='" + arr[3] + "' and gxCode='" + arr[1] + "')");
                sb.Append(" and w.userCode='" + arr[2] + "' and u.baseCode='" + userLogin.UserInfo().baseCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                table.Columns.Add("gxCode");
                table.Columns.Add("cgxCode");
                if (table.Rows.Count > 0)
                {
                    sb.Clear();
                    sb.Append("select * from fun_CommonData_Info");
                    var cTable = cmd.GetDataTable(sb.ToString());
                    List<string> relist = new List<string>();
                    foreach (DataRow r in table.Rows)
                    {
                        string type = r["wType"].ToString();
                        if (!relist.Contains(type))
                        {
                            var dic = new Dictionary<string, string>();
                            var dr = table.Select("wType='" + type + "'");
                            double total = 0;
                            int num = 0;
                            foreach (DataRow drow in dr)
                            {
                                total += double.Parse(drow["total"].ToString());
                                num += int.Parse(drow["num"].ToString());
                            }
                            var wArr = type.Split('-');
                            string gxName = "", bgName = "";
                            var qdr = cTable.Select("cCode='" + wArr[0] + "'");
                            if (qdr.Length > 0)
                            {
                                gxName = qdr[0]["cName"].ToString();
                            }
                            qdr = cTable.Select("cCode='" + wArr[1] + "'");
                            if (qdr.Length > 0)
                            {
                                bgName = qdr[0]["cName"].ToString();
                            }
                            dic["userName"] = string.Format("{0}({1})", r["userName"].ToString(), r["userCode"].ToString());
                            dic["gxName"] = gxName;
                            dic["bgName"] = bgName;
                            dic["num"] = num.ToString();
                            dic["total"] = total.ToString();
                            list.Add(dic);
                            relist.Add(type);
                        }

                    }
                }

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取生产报工信息(新)
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getNewProductReportWage(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var arr = condition.Split(',');
                List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
                StringBuilder sb = new StringBuilder();
                sb.Append("select w.*,u.userName from pw_employeeWage_info w ");
                sb.Append("inner join sys_users_info u on u.userCode=w.userCode ");
                sb.Append("where memo ");
                sb.Append("in(select memo from pi_ProductBaogong_info where plCode='" + arr[0] + "'");
                sb.Append(" and userCode='" + arr[2] + "' and happenDate='" + arr[3] + "' and gxCode='" + arr[1] + "')");
                sb.Append(" and w.userCode='" + arr[2] + "' and u.baseCode='" + userLogin.UserInfo().baseCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                table.Columns.Add("gxCode");
                table.Columns.Add("cgxCode");
                if (table.Rows.Count > 0)
                {
                    sb.Clear();
                    sb.Append("select * from fun_CommonData_Info");
                    var cTable = cmd.GetDataTable(sb.ToString());
                    List<string> relist = new List<string>();
                    foreach (DataRow r in table.Rows)
                    {

                        string type = r["wType"].ToString();
                        var dic = new Dictionary<string, string>();
                        var wArr = type.Split('-');
                        string gxName = "", bgName = "";
                        var qdr = cTable.Select("cCode='" + wArr[0] + "'");
                        if (qdr.Length > 0)
                        {
                            gxName = qdr[0]["cName"].ToString();
                        }
                        qdr = cTable.Select("cCode='" + wArr[1] + "'");
                        if (qdr.Length > 0)
                        {
                            bgName = qdr[0]["cName"].ToString();
                        }
                        dic["userName"] = string.Format("{0}({1})", r["userName"].ToString(), r["userCode"].ToString());
                        dic["gxName"] = gxName;
                        dic["bgName"] = bgName;
                        dic["createtime"] = r["createtime"].ToString();
                        dic["num"] = r["num"].ToString();
                        dic["total"] = r["total"].ToString();
                        list.Add(dic);


                    }
                }

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除奖惩绩效
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelWageOther(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                DbWageOther wage = new DbWageOther();
                wage.id = int.Parse(dataId);
                wage.isDel = 1;
                wage.delDate = getNow();
                wage.deluser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Data = wage;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产报工绩效
        /// </summary>
        /// <param name="dJson">报工数据</param>
        /// <param name="mCode">编码</param>
        /// <param name="list">数据集集合</param>
        /// <returns></returns>
        public ReturnResult ProductReportMoney(JObject dJson, string mCode, ref List<OperateModel> list)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                #region 获取计算公式
                sb.Append("select cValues,specFile from fun_CommonData_Info where ");
                sb.Append("parentCode='" + dJson["gxCode"].ToString() + "'");
                sb.Append(" and specFile ='" + dJson["wType"].ToString() + "'");
                var wageTable = cmd.GetDataTable(sb.ToString());
                if (wageTable.Rows.Count < 1)
                {
                    rsl.Message = "没有该工序的绩效计算公式";
                    return rsl;
                }
                #endregion

                #region 获取生产工序的表单数据
                sb.Clear();
                sb.Append("select gxContents from pi_ProductionPlan_process where");
                sb.Append(" plCode='" + dJson["plCode"].ToString() + "' and gxCode='" + dJson["gxCode"].ToString() + "'");
                var gxFormTable = cmd.GetDataTable(sb.ToString());
                JObject gxJson = new JObject();
                if (gxFormTable.Rows.Count > 0 && gxFormTable.Rows[0][0].ToString() != "--")
                {
                    gxJson = JsonConvert.DeserializeObject<JObject>(gxFormTable.Rows[0][0].ToString());
                }
                #endregion

                #region 获取生产计划数据
                sb.Clear();
                sb.Append("select * from pi_ProductionPlan_info where plCode='" + dJson["plCode"].ToString() + "'");
                var planTable = cmd.GetDataTable(sb.ToString());
                #endregion

                string msg = "", value = "";

                formatSCGs(wageTable.Rows[0]["cValues"].ToString(), gxJson, planTable, dJson["gxCode"].ToString(), ref value, ref msg);
                if (value == "")
                {
                    rsl.Message = msg;
                    return rsl;
                }

                #region 人员岗位
                var uArr = dJson["userCodes"].ToString().Split(',');
                sb.Clear();
                sb.Append("select * from fun_ProductPosition_info where gxCode='" + dJson["gxCode"].ToString() + "'");
                sb.Append(" and pCode='" + dJson["positionKey"].ToString() + "'");
                var pTable = cmd.GetDataTable(sb.ToString());
                if (pTable.Rows.Count > 0)
                {
                    foreach (string u in uArr)
                    {
                        var up = u.Split('-');
                        string zhanbi = "";
                        foreach (DataRow r in pTable.Rows)
                        {
                            if (r["gwCode"].ToString() == up[1].Trim())
                            {
                                zhanbi = r["zhanbi"].ToString().Split(',')[0];
                                break;
                            }
                        }
                        if (string.IsNullOrWhiteSpace(zhanbi))
                        {
                            rsl.Message = "岗位占比获取失败：" + up[1];
                            return rsl;
                        }
                        double w_num = 1;

                        DbemployeeWage wage = new DbemployeeWage();
                        wage.barCode = "-";
                        wage.userCode = up[0];
                        wage.gangwei = up[1];
                        if (!string.IsNullOrWhiteSpace(dJson["num"].ToString()))
                        {
                            // wage.num = dJson["num"].ToString();
                            w_num = double.Parse(dJson["num"].ToString());
                        }
                        else
                        {
                            // wage.num = "1";
                        }

                        wage.createtime = getNow();
                        wage.memo = mCode;
                        wage.bgType = dJson["wType"].ToString();
                        wage.plCode = dJson["plCode"].ToString();
                        wage.createuser = dJson["createuser"].ToString();
                        if (DateTime.Now.Hour < int.Parse(Tools.ConfigReader.Reader["WageTimeEnd"]))
                        {
                            wage.happenDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                        }
                        else
                        {
                            wage.happenDate = getNowDate();
                        }
                        wage.isdel = 0;
                        wage.uPrice = value;
                        wage.wType = string.Format("{0}-{1}", dJson["gxCode"].ToString(), dJson["wType"].ToString());
                        wage.total = Convert.ToString(double.Parse(value) * double.Parse(zhanbi) * w_num);
                        wage.zhanbi = zhanbi;
                        oper = new OperateModel();
                        oper.Data = wage;
                        oper.Types = OperateModel.OperateType.Add;
                        list.Add(oper);
                    }
                }
                else
                {
                    rsl.Message = "无法获得岗位基础信息";
                    return rsl;
                }
                #endregion
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 员工绩效导出
        /// </summary>
        /// <param name="info"></param>
        /// <param name="plCode"></param>
        /// <returns></returns>
        //public MemoryStream EmployeeWageExcel(string condition)
        //{
        //    MemoryStream ms = null;
        //    try
        //    {
        //        int rCount = 0;
        //        StringBuilder sb = new StringBuilder();
        //        var dRsl = this.EmployeeWageReport(condition);
        //        List<Dictionary<string, object>> dlist = new List<Dictionary<string, object>>();
        //        if (dRsl.Result)
        //        {
        //            dlist = (List<Dictionary<string, object>>)dRsl.Data;
        //        }
        //        NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
        //        //添加一个sheet
        //        NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
        //        IDataFormat dataformat = book.CreateDataFormat();
        //        ICell cell;
        //        sheet1.SetColumnWidth(0, 14 * 256);//宽度设置
        //        sheet1.SetColumnWidth(1, 14 * 256);//宽度设置
        //        sheet1.SetColumnWidth(2, 14 * 256);//宽度设置
        //        sheet1.SetColumnWidth(3, 14 * 256);//宽度设置
        //        sheet1.SetColumnWidth(4, 14 * 256);//宽度设置
        //        var bodyStyle = ExcelBodyStyle(book, true);//单元格样式

        //        NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
        //        cell = row1.CreateCell(rCount);

        //        cell.SetCellValue("员工绩效"); cell.CellStyle = ExcelTitleStyle(book, false);
        //        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2);
        //        sheet1.AddMergedRegion(region);
        //        row1.Height = 550;
        //        rCount++;
        //        foreach (var ud in dlist)
        //        {
        //            row1 = sheet1.CreateRow(rCount);
        //            cell = row1.CreateCell(0);
        //            cell.SetCellValue("人员姓名");
        //            cell.CellStyle = ExcelTitleStyle(book, true, false);
        //            cell = row1.CreateCell(1);
        //            cell.SetCellValue(ud["user"].ToString());
        //            cell.CellStyle = ExcelTitleStyle(book, true, false);
        //            cell = row1.CreateCell(2);
        //            cell.SetCellValue("生产数");
        //            cell.CellStyle = ExcelTitleStyle(book, true, false);
        //            cell = row1.CreateCell(3);
        //            cell.SetCellValue(string.Format("{0}/{1}", ud["yTotal"].ToString(), ud["nTotal"].ToString()));
        //            cell.CellStyle = ExcelTitleStyle(book, true, false);
        //            cell = row1.CreateCell(4);
        //            cell.SetCellValue("金 额");
        //            cell.CellStyle = ExcelTitleStyle(book, true, false);
        //            cell = row1.CreateCell(5);
        //            cell.SetCellValue(ud["total"].ToString());
        //            cell.CellStyle = ExcelTitleStyle(book, true, false);
        //            row1.Height = 450;
        //            var mxList = (List<Dictionary<string, string>>)ud["datas"];
        //            if (mxList.Count > 0)
        //            {
        //                rCount++;
        //                row1 = sheet1.CreateRow(rCount);
        //                cell = row1.CreateCell(0);
        //                cell.SetCellValue("日期");
        //                cell.CellStyle = bodyStyle;
        //                cell = row1.CreateCell(1);
        //                cell.SetCellValue("合格数");
        //                cell.CellStyle = bodyStyle;
        //                cell = row1.CreateCell(2);
        //                cell.SetCellValue("不合格数");
        //                cell.CellStyle = bodyStyle;
        //                cell = row1.CreateCell(3);
        //                cell.SetCellValue("单价");
        //                cell.CellStyle = bodyStyle;
        //                cell = row1.CreateCell(4);
        //                cell.SetCellValue("绩效金额");
        //                cell.CellStyle = bodyStyle;
        //                row1.Height = 470;
        //                foreach (var d in mxList)
        //                {
        //                    rCount++;
        //                    #region 明细数据表
        //                    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(rCount);
        //                    cell = rowtemp.CreateCell(0);
        //                    cell.CellStyle = bodyStyle;
        //                    cell.SetCellValue(d["date"].ToString());
        //                    cell = rowtemp.CreateCell(1);
        //                    cell.CellStyle = bodyStyle;
        //                    cell.SetCellValue(d["yNum"].ToString());
        //                    cell = rowtemp.CreateCell(2);
        //                    cell.CellStyle = bodyStyle;
        //                    cell.SetCellValue(d["nNum"].ToString());
        //                    cell = rowtemp.CreateCell(3);
        //                    cell.CellStyle = bodyStyle;
        //                    cell.SetCellValue(d["uPrice"].ToString());
        //                    cell = rowtemp.CreateCell(4);
        //                    cell.CellStyle = bodyStyle;
        //                    cell.SetCellValue(d["total"].ToString());
        //                    rowtemp.Height = 500;
        //                    #endregion

        //                }
        //            }
        //            rCount++;
        //        }


        //        ms = new System.IO.MemoryStream();
        //        book.Write(ms);
        //        ms.Seek(0, SeekOrigin.Begin);

        //    }
        //    catch (Exception ex)
        //    {
        //        var p = ex;
        //    }

        //    return ms;
        //}
        public MemoryStream EmployeeWageExcel(string condition)
        {
            MemoryStream ms = null;
            try
            {
                StringBuilder sb = new StringBuilder();
                var type = "";
                #region 
                sb.Append("select * from V_Wage_PlanDetail where isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    type = json["parentName"].ToString();
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append(" convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }
                sb.Append(" order by userCode,gxCode ");
                #endregion

                var table = cmd.GetDataTable(sb.ToString());

                #region 数据处理，去掉无效小数位 已注释
                //foreach (DataRow dr in table.Rows)
                //{
                //    if (dr["sumNum"] != null )
                //    {
                //        dr["sumNum"] = string.Format("{0:0.##}", Convert.ToDecimal(dr["sumNum"].ToString()));
                //    }
                //    if (dr["yNum"] != null )
                //    {
                //        dr["yNum"] = string.Format("{0:0.##}", Convert.ToDecimal(dr["yNum"].ToString()));
                //    }
                //    if (dr["nNum"] != null )
                //    {
                //        dr["nNum"] = string.Format("{0:0.##}", Convert.ToDecimal(dr["nNum"].ToString()));
                //    }
                //}
                #endregion

                if (!string.IsNullOrWhiteSpace(type))
                    ms = sysBLL.CreateExcel(table.Rows[0]["parentCode"].ToString(), table);
                else
                    ms = sysBLL.CreateExcel("", table);
            }
            catch (Exception ex)
            {
                var p = ex;
            }

            return ms;
        }

        /// <summary>
        /// 员工生产明细数据显示
        /// </summary>
        /// <param name="condition">检索条件</param>
        /// <returns></returns>
        public ReturnResult GetEmployeeProInfo(string condition)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select * from V_Wage_EmpWage where isdel=0 ");
                #region 检索条件
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                foreach (JProperty obj in json.Properties())
                {
                    if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        if (!string.IsNullOrWhiteSpace(sb.ToString()))
                        {
                            sb.Append(" and ");
                        }
                        if (obj.Name == "sDate")
                        {
                            sb.Append(" convert(date,happendate)>='" + json["sDate"].ToString() + "' ");
                        }
                        else if (obj.Name == "eDate")
                        {
                            sb.Append(" convert(date,happendate)<='" + json["eDate"].ToString() + "' ");
                        }
                        else
                        {
                            sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                        }
                    }
                }
                #endregion

                var table = cmd.GetDataTable(sb.ToString());

                rsl.Data = table;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }


    }
}
